package com.xqx.mapper;

import com.xqx.pojo.User;
import org.apache.ibatis.annotations.*;
import org.apache.ibatis.jdbc.SQL;
import org.apache.ibatis.scripting.xmltags.ForEachSqlNode;

import java.util.List;
import java.util.Map;

/**
 * @author：xingquanxiang createTime：2019/10/23 11:25
 * description:
 */
public interface UserMapper {

    class UserMapperProvider {
        public String findUser(User user) {
            return new SQL(){{
                SELECT("*");
                FROM("user");
                if(user.getId()!=null){
                    WHERE("id = #{id}");
                }
                if(user.getName()!=null){
                    WHERE("name = #{name}");
                }
                //从这个toString可以看出，其内部使用高效的StringBuilder实现SQL拼接
            }}.toString();
        }

        public String delSql(Map map){
            return new SQL(){{
                DELETE_FROM("user");
                int[] ids  = (int[])map.get("array");
                StringBuilder sb = new StringBuilder();
                sb.append("id in (");
                for (int i = 0; i < ids.length; i++) {
                    sb.append(ids[i]);
                    if (i!=ids.length-1) {
                        sb.append(",");
                    }
                }
                sb.append(")");
                WHERE(sb.toString());

            }}.toString();
        }
    }

    @SelectProvider(type = UserMapperProvider.class, method = "findUser")
    User findByCondition(User user);

    @Select("select * from user")
    @Results(@Result(column = "image_url", property = "imageUrl"))
    List<User> findAll();

    @Select("select * from user where name like concat(concat('%',#{name}),'%')")
    List<User> findLikeName(String name);

    /**
     * 插入数据后 获取自增主键id值
     * @param user
     */
    @Insert("insert into user(name,money,image_url) values(#{name},#{money},#{imageUrl})")
    @Options(useGeneratedKeys=true,keyProperty = "id", keyColumn="id")
    void save(User user);

    @Update("update user set money=#{money} where name=#{name}")
    int updateMoneyByName(User user);

    @DeleteProvider(type = UserMapperProvider.class, method = "delSql")
    int delById(int[] ids);
}
